﻿using System;
using sinetd;

namespace ServerGUI
{
    public partial class MainForm : System.Windows.Forms.Form
    {
        #region Server

        private Server srv;

        private void serverStart()
        {
            if (srv.Start())
            {
                writeToLog("ServerGUI.Start", "started ...");
            }
            else
            {
                writeToLog("ServerGUI.Start", "already running!");
            }
        }

        private void serverStop()
        {
            if (srv.Stop())
            {
                writeToLog("ServerGUI.Stop", "stoped ...");
            }
            else
            {
                writeToLog("ServerGUI.Stop", "nothing to stop");
            }
        }

        #endregion

        public MainForm()
        {
            InitializeComponent();
            this.Icon = sinetd.Utilities.Assembly.GetIconLarge(sinetd.Utilities.Process.GetExeName(), 0);

            srv = new Server("ServerGUI.config.xml");
            srv.MessageLog += new Server.MessageLogEventHandler(writeToLog);
        }

        private void MainForm_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            srv.MessageLog -= new Server.MessageLogEventHandler(writeToLog);
            serverStop();
        }

        #region Button events

        private void button_start_Click(object sender, EventArgs e)
        {
            serverStart();
        }

        private void button_stop_Click(object sender, EventArgs e)
        {
            //cause: blocking app on writeToLog
            new System.Threading.Thread(() => { serverStop(); }).Start();
            writeToLog("ServerGUI.Stop", "trying to stop ...");
        }

        private void button_clear_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }

        #endregion

        private void writeToLog(string msgType, string msgText)
        {
            if (listBox1.InvokeRequired)
            {
                listBox1.Invoke(new Server.MessageLogEventHandler(writeToLog), new object[] { msgType, msgText });
            }
            else
            {
                listBox1.Items.Add("[" + msgType + "] " + msgText);
                
                if (scrollToLastToolStripMenuItem.Checked)
                {
                    int c = listBox1.Items.Count;
                    if (c > listBox1.Height / listBox1.ItemHeight)
                    {
                        listBox1.SelectedIndex = c - 1;
                        listBox1.SelectedIndex = -1;
                    }
                }
            }
        }
    }
}
